<template>
  <div class="flexContent">
    <div class="searchBox">
      <!-- 供应商档案 -->
      <el-form class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="名称">
                  <el-input v-clearEmoji v-model.trim="serData.name" clearable style="width: 95%" placeholder="编号/名称"
                    @keyup.enter.native="serchFn" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="状态">
                  <el-select v-model="serData.status" popper-class="eloption" clearable style="width: 95%"
                    placeholder="状态">
                    <el-option v-for="sta1 in staOptions" :key="sta1.id" :value="sta1.id" :label="sta1.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="供应商类型">
                  <el-select v-model="serData.type" clearable popper-class="eloption" style="width: 95%"
                    placeholder="供应商类型">
                    <el-option v-for="sta1 in staOptions2" :key="sta1.id" :value="sta1.id" :label="sta1.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="10" :xl="6">
                <el-form-item label="更新日期">
                  <el-date-picker v-model="date" style="width: 95%" type="daterange" unlink-panels range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="serchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" v-has="'supply_add'" @click="addFn">新增</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1" style="width: 100%"
          height="100%" :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" align="center"
          size="medium">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="supplierNum" title="供应商编号"
            :min-width="elTableAdaptationWidth('requireNumber', supplierList) + 20" />
          <vxe-column field="name" title="名称" :min-width="elTableAdaptationWidth('name', supplierList)" />
          <vxe-column field="type" title="供应商类型" min-width="120">
            <template v-slot="{ row }">
              <span v-if="row.type === '0'">供应商</span>
              <span v-if="row.type === '1'">生产厂家</span>
            </template>
          </vxe-column>
          <vxe-column field="linkPerson" title="联系人" min-width="150" />
          <vxe-column field="region" title="省市区域" :min-width="elTableAdaptationWidth('region', supplierList)" />
          <vxe-column field="address" :min-width="elTableAdaptationWidth('address', supplierList)" title="详细地址" />
          <vxe-column field="updateTime" min-width="150" title="更新日期">
            <template v-slot="{ row }">
              <span>{{ row.updateTime | parseTime }}</span>
            </template>
          </vxe-column>
          <vxe-column title="状态" width="100">
            <template v-slot="{ row }">
              <el-tag v-if="row.status === '0'" disabled type="primary" plain size="small">经营中</el-tag>
              <el-tag v-if="row.status === '1'" disabled type="info" plain size="small">已暂停</el-tag>
            </template>
          </vxe-column>
          <vxe-column v-if="$showFn(['supply_detail', 'supply_edit', 'supply_del', 'supply_addUser',])" title="操作"
            fixed="right" width="250">
            <template v-slot="{ row }">
              <el-button type="text" style="margin-right: 5px; color: rgb(175, 5, 184)"
                @click.stop="associatedUser(row)" v-has="'supply_addUser'">关联用户</el-button>
              <el-button type="text" style="margin-right: 5px; color: rgb(0, 132, 255)" @click.stop="getDetail(row)"
                v-has="'supply_detail'">详情</el-button>
              <el-button slot="reference" style="color: rgb(0, 132, 255); margin-right: 5px" type="text"
                @click.stop="edit(row)" v-has="'supply_edit'">修改</el-button>
              <el-button type="text" :disabled="row.status !== '1'" style="margin-right: 5px; color: red"
                @click="$delFn('供应商', del, row)" v-has="'supply_del'">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog title="关联用户" :visible.sync="showDialog" width="30%">
      <el-form>
        <el-form-item label="用户">
          <el-select v-model="userId" clearable popper-class="eloption" filterable placeholder="请选择用户">
            <el-option v-for="item in userList" :key="item.id" :label="item.employeeName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelFn">取 消</el-button>
        <el-button class="addBtn" @click="bindUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSupplierList,
  getValidUserList,
  getSupplierUserId,
  bindUser,
  delBindUser,
} from "@/api/supplier";
import { delScm } from "@/api/scm";
export default {
  name: "SupplierInfo",
  data() {
    return {
      width: "50%",
      title: "新增",
      showDialog: false,
      userId: "",
      shopList: [],
      userList: [],
      name: "",
      sta: "",
      isSearch: false,
      staOptions: [
        {
          id: "0",
          name: "经营中",
        },
        {
          id: "1",
          name: "已暂停",
        },
      ],
      staOptions2: [
        {
          id: "0",
          name: "供应商",
        },
        {
          id: "1",
          name: "生产厂家",
        },
      ],
      date: [],
      serData: {
        name: "",
        status: "",
        type: "",
        maxDate: "",
        minDate: "",
      },
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      supplierList: [],
      posId: "",
      supplierId: "",
      bindState: false,
    };
  },
  created() {
    this.getSupplierList();
  },
  methods: {
    async getSupplierList() {
      if (!this.isSearch) {
        this.serData = {
          name: "",
          status: "",
          type: "",
          maxDate: "",
          minDate: "",
        };
      }
      const res = await getSupplierList({ ...this.page, ...this.serData });
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        this.supplierList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        const $table = this.$refs.xTable1
        $table.loadData(this.supplierList);
        console.log("supplierList", this.supplierList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async serchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.serData.maxDate = this.date?.length ? this.date[1] : "";
      this.serData.minDate = this.date?.length ? this.date[0] : "";
      this.getSupplierList();
    },
    resetFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.date = [];
      this.isSearch = false;
      this.serData = {
        name: "",
        status: "",
        type: "",
        maxDate: "",
        minDate: "",
      };
      this.getSupplierList();
    },
    addFn() {
      this.$router.push("supplierAdd");
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getSupplierList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getSupplierList();
    },
    async getDetail(row) {
      this.$router.push({
        path: "supplierDetail",
        query: {
          type: "detail",
          id: row.id,
        },
      });
    },
    async edit(row) {
      this.$router.push({
        path: "supplierEdit",
        query: {
          type: "edit",
          id: row.id,
        },
      });
    },
    async del(row) {
      const res = await delScm({ id: row.id });
      if (res.code === 200) {
        this.$message.success(res.message);
        if (this.supplierList.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.getSupplierList();
      } else {
        // this.$message.error(res.message);
      }
    },
    async getValidUserList() {
      const res = await getValidUserList();
      if (res.code === 200) {
        //
        this.userList = res.data;
        console.log(this.userList, "userList");
      }
    },
    async getSupplierUserId(id) {
      const res = await getSupplierUserId({ supplierId: id });
      if (res.code === 200) {
        this.userId = res.data.id;
        this.bindState = true;
        console.log(this.userId, "userId");
        console.log(res.data, "信息");
        this.userList.unshift(res.data);
      } else {
        this.bindState = false;
        this.userId = "";
        console.log(res);
      }
      console.log(this.bindState, "this.bindState");
    },
    associatedUser(row) {
      //
      this.getValidUserList();
      this.showDialog = true;
      this.getSupplierUserId(row.id);
      this.supplierId = row.id;
    },
    async bindUser() {
      // 判断是否为初次绑定
      console.log(this.userId, "this.userId");
      if (!this.bindState && !this.userId) {
        // 初次绑定且没选值 直接关闭
        this.showDialog = false;
        console.log("初次绑定且没选值");
        return;
      } else if (this.userId) {
        // 绑定选值了 调绑定
        console.log("绑定选值了");
        console.log(this.userId, "this.userId");
        const res = await bindUser({
          userId: this.userId,
          supplierId: this.supplierId,
        });
        if (res.code === 200) {
          this.$message.success(res.message);
          this.showDialog = false;
        } else {
          // this.$message.error(res.message);
        }
        console.log("res1", res);
      } else {
        // 没选值 调删除
        console.log("没选值");
        console.log(this.userId, "this.userId");
        const res = await delBindUser({
          userId: this.userId,
          supplierId: this.supplierId,
        });
        if (res.code === 200) {
          this.$message.success(res.message);
          this.showDialog = false;
        } else {
          // this.$message.error(res.message);
        }
        console.log("res2", res);
      }
    },
    cancelFn() {
      this.showDialog = false;
      this.userId = "";
      this.supplierId = "";
    },
  },
};
</script>

<style lang="scss" scoped></style>
